package com.qf.coupon;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.qf.coupon.limit.ILimit;
import com.qf.coupon.rule.IRule;
import com.qf.entity.Coupon;

import java.lang.reflect.Field;

public class CouponUtil {

    /**
     * 根据优惠券动态解析出优惠规则的对象
     * @param coupon
     * @return
     */
    public static IRule parseDynamicRuleField(Coupon coupon) {

        //获得优惠券的规则JSON
        //{"ruleClass":"com.qf.coupon.rule.impl.ManJianRule",
        // "fields":[{"name":"must","value":"1000"},{"name":"jian","value":"2"}]}
        String ruleInfo = coupon.getRuleInfo();
        IRule rule = parseObject(ruleInfo, 0);
        return rule;
    }

    /**
     * 根据优惠券动态解析优惠券的限制对象
     * @param coupon
     * @return
     */
    public static ILimit parseDynamicLimitField(Coupon coupon) {
        String limitInfo = coupon.getLimitInfo();
        ILimit limit = parseObject(limitInfo, 1);
        return limit;
    }

    /**
     * type 0-规则 1-限制
     * @param jsonInfo
     * @param type
     * @return
     */
    private static <T> T parseObject(String jsonInfo, Integer type) {
        //解析json
        JSONObject jsonObject = JSON.parseObject(jsonInfo);

        //解析出实体类
        String ruleClassStr = jsonObject.getString(type == 0 ? "ruleClass" : "limitClass");

        //获得动态属性字段
        JSONArray fieldsJson = jsonObject.getJSONArray("fields");

        T t = null;
        try {
            //反射创建规则对象
            Class<?> ruleClass = Class.forName(ruleClassStr);
            t = (T) ruleClass.newInstance();

            //给该对象设置属性
            for (int i = 0; i < fieldsJson.size(); i++) {

                //获得每个属性字段
                JSONObject fieldJson = fieldsJson.getJSONObject(i);
                //获得属性的名称和属性的值
                String name = fieldJson.getString("name");//must
                String value = fieldJson.getString("value");

                //反射将动态的属性值放入对象中
                Field field = ruleClass.getDeclaredField(name);
                field.setAccessible(true);//授权，可以操作私有成员

                //类型的判定
                if (field.getType() == Integer.class || field.getType() == int.class){
                    field.set(t, Integer.parseInt(value));
                } else if(field.getType() == Double.class || field.getType() == double.class){
                    field.set(t, Double.parseDouble(value));
                } else {
                    field.set(t, value);
                }
            }
        } catch (Exception e) {
//            e.printStackTrace();
        }

        return t;
    }
}
